/**
 * WebSocket开发环境测试工具
 * 用于验证WebSocket连接是否正常工作
 */

import SockJS from 'sockjs-client';
import { Client } from '@stomp/stompjs';

export const testWebSocketConnection = () => {
  console.log('=== WebSocket连接测试开始 ===');
  
  const serverUrl = window.location.origin;
  const wsUrl = `${serverUrl}/ws`;
  
  console.log(`尝试连接到: ${wsUrl}`);
  
  const client = new Client({
    webSocketFactory: () => new SockJS(wsUrl),
    
    onConnect: () => {
      console.log('✅ WebSocket连接成功！');
      console.log('连接URL:', wsUrl);
      console.log('连接状态:', client.connected);
      
      // 测试订阅一个主题
      const testSubscription = client.subscribe('/topic/test', (message) => {
        console.log('收到测试消息:', message.body);
      });
      
      console.log('✅ 订阅测试主题成功');
      
      // 5秒后断开连接
      setTimeout(() => {
        testSubscription.unsubscribe();
        client.deactivate();
        console.log('🔄 测试完成，连接已断开');
      }, 5000);
    },
    
    onDisconnect: () => {
      console.log('🔌 WebSocket连接已断开');
    },
    
    onStompError: (frame) => {
      console.error('❌ WebSocket STOMP错误:', frame);
    },
    
    debug: (str) => {
      console.log('🔍 WebSocket Debug:', str);
    },
    
    reconnectDelay: 5000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000,
  });
  
  try {
    client.activate();
    console.log('🚀 正在激活WebSocket连接...');
  } catch (error) {
    console.error('❌ WebSocket连接失败:', error);
  }
};

// 在浏览器控制台中运行测试
// 使用方法: testWebSocketConnection()
window.testWebSocketConnection = testWebSocketConnection;

export default testWebSocketConnection;